#include "Viewer.h"

Viewer::Viewer(){
	InitializeCriticalSection(&locker);
	hMenu = CreateEvent(NULL, true, false, NULL);
	hMenuUnlock = CreateEvent(NULL, true, false, NULL);

	SetEvent(hMenu);
}

void Viewer::lock(){
	EnterCriticalSection(&locker);
}

void Viewer::unlock(){
	LeaveCriticalSection(&locker);
}

void Viewer::wait(){
	SetEvent(hMenuUnlock);

	while(WaitForSingleObject(hMenu, 0) != WAIT_OBJECT_0)
		Sleep(100);
};

int Viewer::print(char *format, ...){
	this->wait();
	this->lock();

	char buffer[1024];
	va_list args;
	va_start (args, format);
	vsprintf (buffer,format, args);
	
	int r = printf(buffer);

	va_end (args);

	this->unlock();

	return r;
}

int Viewer::printn(char *format, ...){
	char buffer[1024];
	va_list args;
	va_start (args, format);
	vsprintf (buffer,format, args);
	
	int r = printf(buffer);

	va_end (args);

	return r;
}

int Viewer::inputc(bool blocking){
	if(blocking) {
		this->wait();
		this->lock();
	}

	fflush(stdin);
	char c = getchar();
	
	if(blocking) this->unlock();

	return c;
}

char *Viewer::input(){
	this->wait();
	this->lock();

	fflush(stdin);
	char *c = new char[1024];
	gets(c);

	this->unlock();
	return c;
}

